<template>
  <div class="purchaseorder">
    <searchCard @onSearch="searchFn" @onReset="resetFn">
      <el-form :model="purchaseorderFrom" label-width="auto" inline @keyup.enter="searchFn">
        <el-form-item label="到货日期：">
          <el-date-picker v-model="value1" type="daterange" range-separator="-" start-placeholder="开始时间"
            end-placeholder="结束时间" @change="timeChangeFn" />
        </el-form-item>
        <el-form-item label="制作单位：">
          <pb-select v-model="purchaseorderFrom.tenantId" placeholder="请选择制作单位" keys="tenantId" label="tenantName"
            :options="kitchenList" @change="changetenantIdFn" />
        </el-form-item>
        <el-form-item label="采购类型：">
          <pb-check :list="classList" @change="changeCheck($event)"></pb-check>
        </el-form-item>
      </el-form>
    </searchCard>
    <div class="flex-1">
      <pb-card padding="0" height="100%">
        <ContentOperation style="justify-content: left;margin-left: 12px;align-items: center;color: rgba(0, 0, 0, 0.55)"
          v-show="false">
          <span class="m-r3">当前选中 {{ batchList && batchList.length > 0 ? batchList.length : 0 }} 行</span>
          <div class="m-r4" v-hasPerm="'center:purchaseorder:batchexamine'">
            <PopconfirmButton @confirm="BatchBtnFn('1')" text="批量审核">
            </PopconfirmButton>
          </div>
          <div v-hasPerm="'center:purchaseorder:batchrevoke'">
            <PopconfirmButton @confirm="BatchBtnFn('2')" text=" 批量撤销">
            </PopconfirmButton>
          </div>
        </ContentOperation>
        <div class="content-box">
          <div class=" main-box ">
            <pb-table :column="planColumn" :tableData="purchaseorderData" :bottomElement="['pb-page']" :indexWidth="60"
              @SelectionChange="handleSelectionChange($event)" :selectionShow="true">
              <template #examineStatus="{ row }">
                {{ getexamineStatusTextFn(row.examineStatus) }}
              </template>
              <template #operate="{ row }">
                <!-- <PopconfirmButton v-hasPerm="'center:purchaseorder:revoke'" @confirm="OrderOrderRevokeFn(row)" text="撤销" v-if="row.examineStatus == '3pass'">
                </PopconfirmButton>
                <p class="divider mr-2 ml-2" v-if="row.examineStatus == '3pass'"></p>
                <PopconfirmButton v-hasPerm="'center:purchaseorder:examine'" @confirm="OrderExamineFn(row)" text="审核" v-if="row.examineStatus == '1wait_examine'">
                </PopconfirmButton>
                <p class="divider mr-2 ml-2" v-if="row.examineStatus == '1wait_examine'"></p> -->
                <!-- <PopconfirmButton @confirm="exportexcelFn(row)" text="导出" v-if="row.examineStatus !== '1wait_examine'">
                </PopconfirmButton>
                <p class="divider mr-2 ml-2" v-if="row.examineStatus !== '1wait_examine'"></p> -->
                <!-- v-hasPerm="'center:purchaseorder:batchrevoke'" -->
                <div class="flex">
                  <div v-hasPerm="'center:purchaseorder:export'">
                    <PopconfirmButton @confirm="exportexcelFn(row)" text="导出">
                    </PopconfirmButton>
                    <p class="divider mr-2 ml-2"></p>
                  </div>
                  <pb-button v-hasPerm="'center:purchaseorder:view'" text size="small"
                    @click="onDetailsFn(row)">明细</pb-button>
                </div>
              </template>
            </pb-table>
            <pb-pagination v-model:currentPage="pages.currentPage" v-model:pageSize="pages.pageSize"
              @onChange="onPagesChange" :total="pages.total"></pb-pagination>
          </div>
        </div>
      </pb-card>
    </div>
    <Details ref="refDetails" />
  </div>
</template>
<script setup lang="ts">
import { formattedDate } from '@/utils/moment'
import {
  GetOrderListApi, ExportOrderBlodApi,
  GetkitchenListApi, GetOrderExamineApi, GetOrderRevokeApi, ExamineOrderBatchApi, RevokeOrderBatchApi
} from '@/api/Purchasing'
import { createMessage } from "@/Public-UIlibrary/pb-message/method";
import { clearObjKey } from '@/utils/fliter'
import Details from './components/detail.vue'
const BatchBtnFn = (TypeNum: string) => {
  if (!batchList.value || batchList.value.length == 0) return createMessage({
    message: '请选择需要操作的数据！',
    type: 'error'
  })
  let arr: any = []
  batchList.value.map((el: any) => {
    arr.push(el.purchaseOrderId)
  })
  if (TypeNum == '1') {
    ExamineOrderBatchApi({
      purchaseOrderIdList: arr
    }).then(res => {
      if (res.code == 2000) {
        createMessage({
          message: '批量审核成功'
        })
        GetOrderListFn()
      }
    })
  } else {
    RevokeOrderBatchApi({
      purchaseOrderIdList: arr
    }).then(res => {
      if (res.code == 2000) {
        createMessage({
          message: '批量撤销成功'
        })
        GetOrderListFn()
      }
    })
  }

}
const batchList = ref([] as any)
const handleSelectionChange = (val: any) => {
  batchList.value = val;
}
const OrderOrderRevokeFn = (row: any) => {
  GetOrderRevokeApi({
    purchaseOrderId: row.purchaseOrderId
  }).then(res => {
    if (res.code == 2000) {
      createMessage({
        message: '撤销通过'
      })
      GetOrderListFn()
    }
  })
}
const OrderExamineFn = (row: any) => {
  GetOrderExamineApi({
    purchaseOrderId: row.purchaseOrderId
  }).then(res => {
    if (res.code == 2000) {
      createMessage({
        message: '审核通过'
      })
      GetOrderListFn()
    }
  })
}
const getexamineStatusTextFn = (Status: String) => {
  if (Status == '0uncommitted') {
    return '待提交'
  } else if (Status == '1wait_examine') {
    return '待审核'
  } else if (Status == '2fail') {
    return '未通过'
  } else if (Status == '3pass') {
    return '已通过'
  }
}
const refDetails = ref(null as any)
const onDetailsFn = (row: any) => {
  refDetails.value.show(row)
}
const exportexcelFn = (row: any) => {
  ExportOrderBlodApi({
    purchaseOrderId: row.purchaseOrderId
  }).then((response: any) => {
    const disposition = response.headers['content-disposition'];
    // const filenameMatch = disposition.match(/filename*=utf-8''\s*([^;]+)/); 没用的东西
    const parts = disposition.split("filename*=utf-8''"); // 注意这里的分割字符串，它包含了一个空的单引号来匹配格式
    const encodedFilenamePart = parts[1] ? parts[1].split(';')[0] : null; // 分割出可能包含文件名的部分，并截取到下一个分号之前
    let decodedFilename = ''
    if (encodedFilenamePart) {
      // 解码文件名
      decodedFilename = decodeURIComponent(encodedFilenamePart);
      decodedFilename = decodedFilename.replace(/\(.*?\)/, '');
      // 输出解码后的文件名
      console.log("Decoded filename:", decodedFilename);
    } else {
      decodedFilename = "订货单" + new Date().getTime() + '.xlsx'
      // 如果没有找到包含文件名的部分，输出警告信息
      // console.warn("No filename part found in the Content-Disposition header using the simplified method.");
    }
    let blob = new Blob([response.data]);
    let downloadElement = document.createElement("a");
    let href = window.URL.createObjectURL(blob); //创建下载的链接
    // console.log(href, '22href')
    downloadElement.href = href;
    downloadElement.download = decodedFilename; //下载后文件名
    document.body.appendChild(downloadElement);
    downloadElement.click(); //点击下载
    document.body.removeChild(downloadElement); //下载完成移除元素
    window.URL.revokeObjectURL(href); //释放掉blob对象
  })
}
const searchFn = () => {
  GetOrderListFn()
}
const resetFn = () => {
  value1.value = ''
  classList.value.map(el => {
    el.checked = false
  })
  classList.value[0].checked = true
  clearObjKey(purchaseorderFrom)
  GetOrderListFn()
}
const changetenantIdFn = () => {
  GetOrderListFn()
}
const purchaseorderData = ref([])
const changeCheck = (eve: any) => {
  // console.log(eve, '22')
  purchaseorderFrom.purchaseType = eve.val
  GetOrderListFn()
}
const planColumn = [
  {
    key: "deliveryDate",
    name: "到货日期",
  },
  {
    key: "purchaseOrderNo",
    name: "采购单号",
  },
  {
    key: "tenantName",
    name: "制作单位",
  },
  {
    slot: 'examineStatus',
    name: '审核状态'
  },
  {
    key: 'creator',
    name: "创建人",
  }, {
    key: 'purchaseTypeName',
    name: "采购类型",
  }, {
    key: 'createTime',
    name: "创建日期",
  },
  {
    key: 'remark',
    name: '备注'
  },
  {
    width: 180,
    slot: "operate",
    name: "操作",
  },
]
const pageInit = () => ({
  total: 0,
  currentPage: 1,
  pageSize: 10,
});
const pages = ref(pageInit());
const onPagesChange = () => {
  GetOrderListFn()
}
const classList = ref([
  { label: '全部', val: '', checked: true },
  { label: '周采购', val: 'weekPlan', checked: false },
  { label: '月采购', val: 'monthPlan', checked: false },
])
const kitchenList = ref([] as any)
const timeChangeFn = (time: any) => {
  purchaseorderFrom.deliveryStartDate = formattedDate(time[0], 'YYYY-MM-DD')
  purchaseorderFrom.deliveryStopDate = formattedDate(time[1], 'YYYY-MM-DD')
}
const GetOrderListFn = () => {
  GetOrderListApi({
    "currentPage": pages.value.currentPage,
    "pageSize": pages.value.pageSize,
    "sortingFields": [
      {
        "field": "",
        "order": ""
      }
    ],
    ...purchaseorderFrom
  }).then(res => {
    purchaseorderData.value = res.data.records
    pages.value.total = res.data.total
  })
}
const value1 = ref('')
const purchaseorderFrom = reactive({
  deliveryStartDate: '',
  deliveryStopDate: '',
  purchaseType: '',
  tenantId: ''
})
onMounted(() => {
  GetkitchenListApi().then(res => {
    kitchenList.value = res.data
    kitchenList.value.unshift({
      tenantName: '全部',
      tenantId: ''
    })
  })
  GetOrderListFn()
})
</script>
<style lang="scss" scoped>
.purchaseorder {
  .content-box {
    height: 100%;
    display: flex;
    flex-direction: column;

    .main-box {
      padding: 16px;
      box-sizing: border-box;
    }
  }
}
</style>
